package com.wuxuan.algorithm_homework.recursion;

import java.util.HashMap;
import java.util.Map;

/**
 * 递归
 */
public class Recursion {

    /**
     * 递归实现阶乘
     * @param n
     * @return
     */
    public static int factorial(int n) {
        if (n == 0 || n == 1) {
            return 1;
        }

        return n * factorial(n - 1);
    }

    /**
     * 斐波那契数列
     *
     * 0 1 1 2 3 5 8 13 21 34
     * @param n
     * @return
     */
    public static int fibonacci(int n) {
        if (n == 0 || n == 1) {
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    /**
     * 记忆搜索优化-斐波那契数列
     * @param n
     * @return
     */
    public static int fibonacci2(int n) {
        Map<Integer, Integer> map = new HashMap<>();
        //需要用同一个map记录完成计算，故将map传进递归层
        return fibonacci(map, n);
    }

    public static int fibonacci(Map<Integer, Integer> map,int n) {
        //基本情况
        if (n == 0 || n == 1) {
            return n;
        }

        if (map.containsKey(n)) {
            return map.get(n);
        }

        int result = fibonacci(map, n - 1) + fibonacci(map, n - 2);
        map.put(n, result);

        return result;
    }
    public static void main(String[] args) {
        System.out.println(factorial(5));
        System.out.println(fibonacci(5));
        Map<Integer, Integer> map = new HashMap<>();
        System.out.println(fibonacci(map, 5));
    }

}
